<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="招标任务" prop="bidName">
        <el-input
          v-model="queryParams.bidName"
          placeholder="请输入招标任务名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="竞标任务" prop="inviteBidName">
        <el-input
          v-model="queryParams.inviteBidName"
          placeholder="请输入竞标任务名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:oss:add']"
        >新增任务</el-button>
      </el-col>
      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="multiple"
        @click="handleDelete"
        v-hasPermi="['system:oss:remove']"
      >删除</el-button>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false"/>
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="招标任务名" align="center" prop="bidName" />
      <el-table-column label="竞标任务名" align="center" prop="inviteBidName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="judgeStatus"
            @click="comparisonAdd(scope.row)"
          >标书导入</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-arrow-right"
            size="mini"
            @click="startTask(scope.row)"
            v-hasPermi="['system:oss:list']"
          >查重</el-button>
          <el-button
            type="warning"
            plain
            icon="el-icon-info"
            size="mini"
            :disabled="judgeStatus1"
            @click="handleComparisonResult(scope.row)"
          >查看结果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 标书导入对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-row :gutter="6" class="mb8">
        <el-col :span="8">
          <el-upload
          action=""
          :before-remove="beforeRemove"
          multiple="true"
          :limit="1"
          :file-list="fileList"
          :on-change="handleChangeFile"
          :on-success="handleFileSuccess"
          :auto-upload="true"
          :http-request="filsAdd1"
          accept=".docx,.pdf">
            <el-button size="medium" v-hasPermi="['system:oss:upload']">选择上传招标文件<i class="el-icon-upload el-icon--right"></i></el-button>
            <div slot="tip" class="el-upload__tip">支持docx,pdf文件</div>
          </el-upload>
        </el-col>
      </el-row>
      <br/>
      <br/>
      <el-row :gutter="6">
        <el-col :span="8">
        <el-upload
          action=""
          :before-remove="beforeRemove"
          multiple="true"
          :limit="20"
          :file-list="fileList"
          :on-change="handleChangeFile"
          :auto-upload="false"
          accept=".pdf,.docx">
          <el-button size="medium" v-hasPermi="['system:oss:upload']">选择上传竞标文件<i class="el-icon-upload el-icon--right"></i></el-button>
          <div slot="tip" class="el-upload__tip">支持docx,pdf文件上传,并且最多不能超过20个</div>    
        </el-upload>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            plain
            @click="filsAdd2"
            >请点击确认上传</el-button>
        </el-col>
      </el-row>
      <br/>
      <br/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增任务对话框 -->
    <el-dialog :title="title1" :visible.sync="open1" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCheck, getCheck, delCheck, addCheck,addAttachment1,addAttachment2,startCheck, getUserId
} from "@/api/system/check";

export default {
  name: "Check",
  data() {
    return {
      id: undefined,
      userId: '',
      // 服务端地址，一般都是网关的地址
      wsUrl: 'ws://39.98.68.179:8080/websocket/',
      // WebSocket实例
      webSocket: null,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //状态禁用
      judgeStatus: false,
      judgeStatus1: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      checkId: 0,
      // 查重任务表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      title1: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      filesLength:0,
      //存储上传的文件数组
      fileListG:[],
      fileList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        status: undefined,
        projectName: undefined,
        bidName: undefined,
        bidUrl: undefined,
        inviteBidName: undefined,
        inviteBidUrl: undefined,
        createTime: undefined,
        createBy: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUserId();
    //同步处理先获取id，再创建WebSocket连接
    this.initWebSocket();
  },
  destroyed: function () {
    // 在Vue销毁前断开WebSocket服务器连接
    this.webSocket.close();
  },
  methods: {
    /** 查询查重任务列表 */
    getUserId() {
      this.loading = true;
      getUserId().then(response => {
        this.userId = response.data;
        this.loading = false;
      });
    },
    initWebSocket: function () { // 建立连接
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      this.websocket = new WebSocket(this.wsUrl+this.userId);
      this.websocket.onopen = this.websocketOnopen;
      this.websocket.onerror = this.websocketOnerror;
      this.websocket.onmessage = this.websocketOnmessage;
      this.websocket.onclose = this.websocketClose;
    },
    // 连接成功后调用
    websocketOnopen: function () {
      console.log("WebSocket连接成功");
    },
    // 发生错误时调用
    websocketOnerror: function (e) {
      console.log("WebSocket连接发生错误");
    },
    // 接收后端消息（服务器端发送）
    websocketOnmessage: function (e) {
      this.$message("查重任务已完成");
      this.getList();
    },
    // 关闭连接时调用
    websocketClose: function (e) {
      console.log("WebSocket关闭");
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    /**  添加附件管理界面的钩子函数 **/
    handleChangeFile(file,files) {
      //记录文件个数
        this.filesLength=files.length
        if(files.length>20){
          this.$message.error("最多上传20个文件");
          return;
        }
        //存储上传的文件数组
        this.fileListG=files;
    },
    //按钮点击方法触发异步数据请求
    filsAdd1(){
      if(this.filesLength==0){
        this.$message("请添加文件");
        return;
      }
      //比较文件数相同只发送一次异步请求
      if(this.fileListG.length===this.filesLength) {
      //文件发送使用formData
        let formData=new FormData();
        //遍历this.fileListG存到formData
        this.fileListG.forEach(item=>{
        //文件上传的信息存储在file.raw中（你自己打印即可看到）
          formData.append("file",item.raw)
        })
        //后端接口请求
        addAttachment1(this.id,formData).then(res=>{
          //实现消息提示
          this.$modal.msgSuccess("添加成功");
        }).catch(rso=>{
        //失败回调
          console.log(rso,"接口失败")
          throw "上传失败"
        })
      }
    },
    //按钮点击方法触发异步数据请求
    filsAdd2(){
      if(this.filesLength==0){
        this.$message("请添加文件");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '正在上传，请勿操作',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      //比较文件数相同只发送一次异步请求
      if(this.fileListG.length===this.filesLength) {
      //文件发送使用formData
        let formData=new FormData();
        //遍历this.fileListG存到formData
        this.fileListG.forEach(item=>{
        //文件上传的信息存储在file.raw中（你自己打印即可看到）
          formData.append("file",item.raw)
        })
        //后端接口请求
        addAttachment2(this.id,formData).then(res=>{
          loading.close();
          //实现消息提示
          this.$modal.msgSuccess("添加成功");
        }).catch(rso=>{
          loading.close();
          throw "上传失败"
        })
      }
    },
    /** 查询查重任务列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1 = false;
      this.reset();
    },
    cancel1() {
      this.open = false;
      this.getList();
      this.reset();
    },
    /** 查重按钮操作 */
    handleCheck() {
      this.$modal.confirm('确定开始该查重任务？').then(function() {
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("正在查重");
      }).catch(() => {});
    },
    // 确定查重按钮
    startTask(row) {
      this.id = row.id || this.ids;
      if (this.id==null) {
        this.$modal.$message("请先上传招竞标文件");
        return;
      }
      this.open = false;
      this.reset();
      this.$modal.msgSuccess("正在查重");
      startCheck(this.id).then(response => {
        if (response.code==200) {
          this.$modal.msgSuccess("查重任务完成");
          this.getList();
          this.reset();
        }
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addCheck(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open1 = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    // 确定按钮
    submitTask() {
      this.open = false;
      this.reset();
      this.handleCheck();
    },

    // 点击按钮
    click() {
      this.open = false;
      this.reset();
    },
    /** 文件按钮操作 */
    handleFile() {
      this.reset();
      this.open = true;
      this.title = "上传文件";
      this.type = 0;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        status: undefined,
        projectName: undefined,
        bidName: undefined,
        bidUrl: undefined,
        inviteBidName: undefined,
        inviteBidUrl: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 标书导入按钮操作 */
    comparisonAdd(row) {
      if(row.status == "已完成"){
        judgeStatus = true;
      }
      this.id = row.id || this.ids;
      this.reset();
      this.open = true;
      this.title = "添加标书";
    },
    /** 任务结果查询 */
    handleComparisonResult(row) {
      if(row.status == "准备中"){
        judgeStatus1 = true;
      }
      this.id = row.id || this.ids;
      this.$router.push({
        path: '/system/oss-config/index',
        query: {
          //要传的参数
          id: this.id,
        },
    })
    },
    /** 新增任务按钮操作 */
    handleAdd() {
      this.reset();
      this.open1 = true;
      this.title1 = "新增任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCheck(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改查重任务";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除查重任务编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCheck(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/check/export', {
        ...this.queryParams
      }, `check_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
